package com.joysuch.wwyt.api.dataaccess;

import cn.zlg.common.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.io.ByteStreams;
import com.joysuch.wwyt.api.config.entity.DataAccessConfig;
import com.joysuch.wwyt.api.config.entity.DataAccessUrl;
import com.joysuch.wwyt.api.config.service.DataAccessConfigService;
import com.joysuch.wwyt.api.config.service.DataAccessUrlService;
import com.joysuch.wwyt.api.dataaccess.bean.*;
import com.joysuch.wwyt.api.enums.DataAccessTypes;
import com.joysuch.wwyt.api.saferisk.bean.APILoginBean;
import com.joysuch.wwyt.api.saferisk.bean.APIResponseBean;
import com.joysuch.wwyt.bp.bean.BpWorkSafetyPeopleTypeBean;
import com.joysuch.wwyt.bp.entity.*;
import com.joysuch.wwyt.bp.entity.contractor.BpContractor;
import com.joysuch.wwyt.bp.enums.SafetyWorkTypes;
import com.joysuch.wwyt.bp.enums.WorkLevels;
import com.joysuch.wwyt.bp.repository.*;
import com.joysuch.wwyt.core.common.util.SimpleDateFormatCache;
import com.joysuch.wwyt.core.entity.BaseImageRepository;
import com.joysuch.wwyt.core.repository.BaseImageRespositoryDao;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.security.ShiroUser;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.edu.entity.EduTrainningPlan;
import com.joysuch.wwyt.edu.entity.EduTrainningRecord;
import com.joysuch.wwyt.edu.entity.EduTrainningRecordUser;
import com.joysuch.wwyt.edu.repository.EduTrainningPlanDao;
import com.joysuch.wwyt.edu.repository.EduTrainningRecordUserDao;
import com.joysuch.wwyt.risk.bean.RiskPointEvaluationBean;
import com.joysuch.wwyt.risk.bean.RiskPointEvaluationDetailBean;
import com.joysuch.wwyt.risk.bean.RiskPointEvaluationItemBean;
import com.joysuch.wwyt.risk.entity.RiskDistrict;
import com.joysuch.wwyt.risk.entity.RiskPoint;
import com.joysuch.wwyt.risk.repository.RiskDistrictDao;
import com.joysuch.wwyt.risk.service.RiskPointService;
import javafx.util.Pair;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * 申华4家公司数据接入
 *
 * @Author ZhangDong
 * @Date 2020/8/17 14:10
 */
@Service
@Slf4j
public class DataAccessServiceImpl implements DataAccessService {

    @Autowired
    private DataAccessConfigService configService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private EduTrainningPlanDao eduTrainningPlanDao;
    @Autowired
    private BpDepartDao bpDepartDao;
    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private BpEmergencyExercisePlanDao exercisePlanDao;
    @Autowired
    private RiskDistrictDao riskDistrictDao;
    @Autowired
    private RiskPointService riskPointService;
    @Value("${wwyt.file.upload.dir}")
    private String imageUploadPath;
    @Autowired
    private BpContractorStaffDao staffDao;
    @Autowired
    private DataAccessUrlService dataAccessUrlService;
    @Autowired
    private BpProductionFacilityTypeDao facilityTypeDao;
    @Autowired
    private BaseImageRespositoryDao baseImageRespositoryDao;
    @Autowired
    private BpWorkSafetyCertUserDao bpWorkSafetyCertUserDao;
    @Autowired
    private EduTrainningRecordUserDao eduTrainningRecordUserDao;
    private static final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(3, r -> {
        Thread thread = new Thread(r, "data-access worker");
        thread.setDaemon(true);
        return thread;
    });

    /**
     * 1.接口信息验证
     * 登录获取code 用于接口请求密钥申请，账号密码正确则返回一个 code，此 code 有效期为两小时，
     * 其他上报接口中需要Headers中加入code 参数
     * code - config
     */
    @Override
    public Pair<String, DataAccessConfig> getCode() {
        DataAccessConfig config = getConfig();
        if (config == null || !config.getStatus()) return new Pair<>(null, null);
        Pair<Boolean, String> pair = getUrl(DataAccessTypes.INTERFACE_CHECK.getModelName());
        if (!pair.getKey()) return new Pair<>(null, null);
        String loginUrl = pair.getValue();
        String companyName = config.getCompanyName();
        String password = config.getPassword();
        APILoginBean loginBean = new APILoginBean();
        loginBean.setUsername(companyName);
        loginBean.setPassword(password);
        try {
            APIResponseBean response = restTemplate.postForObject(loginUrl, loginBean, APIResponseBean.class);
            if (response.getStatusCode() != HttpStatus.OK.value()) {
                return new Pair<>(null, config);
            }
            return new Pair<>(response.getMessage(), config);
        } catch (RestClientException e) {
            log.error("login fail,companyName:{},password:{}", companyName, password, e);
            return new Pair<>(null, config);
        }
    }

    /**
     * 共用
     * 2.安全防护设备信息(更新频率：有变动就更新)   设备类型为  安全防护设备/安全防护
     * 3.消防设备信息(更新频率：有变动就更新)       设备类型为  消防设备/消防
     * 对应生产装置
     */
    @Override
    public void safeDevice(List<BpProductionFacility> deviceList) {
        if (CollectionUtils.isEmpty(deviceList)) return;
        ShiroUser currentUser = Context.getCurrentUser();
        executor.execute(() -> {
            Context.setCurrentUser(currentUser);
            Pair<String, DataAccessConfig> pair = getCode();
            String code = pair.getKey();
            DataAccessConfig config = pair.getValue();
            if (code == null) return;
            Pair<Boolean, String> safeDevicePair = getUrl(DataAccessTypes.SAFE_DEVICE_INFO.getModelName());
            Pair<Boolean, String> fireControlDevicePair = getUrl(DataAccessTypes.FIRE_CONTROL_DEVICE_INFO.getModelName());
            for (BpProductionFacility facility : deviceList) {
                Long typeId = facility.getType();
                if (typeId == null) continue;
                String facilityName = facilityTypeDao.findNameById(typeId);
                if (facilityName == null) continue;
                if (judge(facilityName)) continue;
                DataAccessBean bean = new DataAccessBean();
                bean.setCorpName(config.getCompanyName());
                bean.setCorpKey(config.getCompanyCode());
                String url = null;
                if (facilityName.equals("安全防护设备") || facilityName.equals("安全防护")) {
                    if (!safeDevicePair.getKey()) continue;
                    url = safeDevicePair.getValue();
                } else if (facilityName.equals("消防设备") || facilityName.equals("消防")) {
                    if (!fireControlDevicePair.getKey()) continue;
                    url = fireControlDevicePair.getValue();
                }
                List<SafeDeviceBean> safeDeviceBeans = Lists.newArrayList(new SafeDeviceBean(facility));
                bean.setDtos(safeDeviceBeans);
                try {
                    APIResponseBean response = rest(code, bean, url);
                    if (response.getStatusCode() != HttpStatus.OK.value()) {
                        log.warn("device data access fail,deviceId:{},cause:{}", facility.getId(), response.getMessage());
                        return;
                    }
                    log.info("device data access success,deviceId:{}", facility.getId());
                } catch (RestClientException e) {
                    log.error("device data access fail,deviceId:{},cause:{}", facility.getId(), e.getMessage());
                }
            }
        });
    }

    /**
     * 4.安全投入信息(更新频率：有变动就更新)
     * 可重复提交
     */
    @Override
    public void safeInput(String formData, String formKeyLabelJson) {
        ShiroUser currentUser = Context.getCurrentUser();
        executor.execute(() -> {
            Context.setCurrentUser(currentUser);
            Pair<String, DataAccessConfig> pair = getCode();
            String code = pair.getKey();
            DataAccessConfig config = pair.getValue();
            if (code == null) return;
            Pair<Boolean, String> pair1 = getUrl(DataAccessTypes.SAFE_INPUT_INFO.getModelName());
            if (!pair1.getKey()) return;
            String url = pair1.getValue();
            DataAccessBeanV bean = getDataAccessBeanV(formData, formKeyLabelJson, config);
            String log1 = JSON.toJSONString(bean);
            try {
                APIResponseBean response = rest(code, bean, url);
                if (response.getStatusCode() != HttpStatus.OK.value()) {
                    log.warn("safe input data access fail,safeInput:{},cause:{}", log1, response.getMessage());
                    return;
                }
                log.info("safe input data access success,safeInput:{}", log1);
            } catch (RestClientException e) {
                log.error("safe input data access fail,safeInput:{},cause:{}", log1, e.getMessage());
            }
        });
    }

    /**
     * 5.企业隐患上报(更新频率：有变动就更新)
     * 可重复提交
     */
    @Override
    public void hiddenDangerReport(String formData, String formKeyLabelJson) {
        ShiroUser currentUser = Context.getCurrentUser();
        executor.execute(() -> {
            Context.setCurrentUser(currentUser);
            Pair<String, DataAccessConfig> pair = getCode();
            String code = pair.getKey();
            DataAccessConfig config = pair.getValue();
            if (code == null) return;
            Pair<Boolean, String> pair1 = getUrl(DataAccessTypes.HIDDEN_DANGER_REPORT.getModelName());
            if (!pair1.getKey()) return;
            String url = pair1.getValue();
            JSONObject formDataObj = JSON.parseObject(formData);
            JSONObject formLabelObj = JSON.parseObject(formKeyLabelJson);
            HiddenDangerReportBean bean = getHiddenDangerReportBean(config, formDataObj, formLabelObj);
            if(bean == null){
                return ;
            }
            String log1 = JSON.toJSONString(bean);
            try {
                APIResponseBean response = rest(code, bean, url);
                if (response.getStatusCode() != HttpStatus.OK.value()) {
                    log.warn("hidden danger data access fail,hiddenDanger:{},cause:{}", log1, response.getMessage());
                    return;
                }
                log.info("hidden danger data access success,hiddenDanger:{}", log1);
            } catch (RestClientException e) {
                log.error("hidden danger data access fail,hiddenDanger:{},cause:{}", log1, e.getMessage());
            }
        });
    }

    /**
     * 6.适用的法律法规标准清单上报(更新频率：有变动就更新)
     * 可重复提交
     */
    @Override
    public void lawStandardReport(String formData, String formKeyLabelJson) {
        ShiroUser currentUser = Context.getCurrentUser();
        executor.execute(() -> {
            Context.setCurrentUser(currentUser);
            Pair<String, DataAccessConfig> pair = getCode();
            String code = pair.getKey();
            DataAccessConfig config = pair.getValue();
            if (code == null) return;
            Pair<Boolean, String> pair1 = getUrl(DataAccessTypes.LAW_STANDARD_REPORT.getModelName());
            if (!pair1.getKey()) return;
            String url = pair1.getValue();
            LawStandardReportBean bean = getLawStandardReportBean(formData, formKeyLabelJson, config);
            String log1 = JSON.toJSONString(bean);
            try {
                APIResponseBean response = rest(code, bean, url);
                if (response.getStatusCode() != HttpStatus.OK.value()) {
                    log.warn("law standard data access fail,lawStandard:{},cause:{}", log1, response.getMessage());
                    return;
                }
                log.info("law standard data access success,lawStandard:{}", log1);
            } catch (RestClientException e) {
                log.error("law standard data access fail,lawStandard:{},cause:{}", log1, e.getMessage());
            }
        });
    }

    /**
     * 7.现场培训(更新频率：有变动就更新)
     * 培训类型为 现场培训
     * //没有参与人员也可以传成功，但是有人员，并且身份证填写正确的情况下仍然报错：  //暂时拿掉参与人员
     */
    @Override
    public void sceneTrain(EduTrainningRecord record) {
        if (record == null) return;
        ShiroUser currentUser = Context.getCurrentUser();
        executor.execute(() -> {
            Context.setCurrentUser(currentUser);
            Pair<String, DataAccessConfig> pair = getCode();
            String code = pair.getKey();
            DataAccessConfig config = pair.getValue();
            if (code == null) return;
            Pair<Boolean, String> pair1 = getUrl(DataAccessTypes.SCENE_TRAIN.getModelName());
            if (!pair1.getKey()) return;
            String url = pair1.getValue();
            DataAccessBeanV bean = getSceneTrainBean(record, config);
            try {
                APIResponseBean response = rest(code, bean, url);
                if (response.getStatusCode() != HttpStatus.OK.value()) {
                    log.warn("scene train data access fail,trainRecordId:{},cause:{}", record.getId(), response.getMessage());
                    return;
                }
                log.info("scene train data access success,trainRecordId:{}", record.getId());
            } catch (RestClientException e) {
                log.error("scene train data access fail,trainRecordId:{},cause:{}", record.getId(), e.getMessage());
            }
        });
    }

    /**
     * 8.作业申请(更新频率：有变动就更新)  审核通过后提交
     */
    @Override
    public void workApply(BpWorkSafetyCert cert) {
        if (cert == null) return;
        ShiroUser currentUser = Context.getCurrentUser();
        executor.execute(() -> {
            Context.setCurrentUser(currentUser);
            Pair<String, DataAccessConfig> pair = getCode();
            String code = pair.getKey();
            DataAccessConfig config = pair.getValue();
            if (code == null) return;
            Pair<Boolean, String> pair1 = getUrl(DataAccessTypes.WORK_APPLY.getModelName());
            if (!pair1.getKey()) return;
            String url = pair1.getValue();
            WorkApplyBean bean = getWorkApplyBean(cert, config);
            try {
                APIResponseBean response = rest(code, bean, url);
                if (response.getStatusCode() != HttpStatus.OK.value()) {
                    log.warn("work apply access fail,certCode:{},cause:{}", cert.getCode(), response.getMessage());
                    return;
                }
                log.info("work apply data access success,certCode:{}", cert.getCode());
            } catch (RestClientException e) {
                log.error("work apply data access fail,certCode:{},cause:{}", cert.getCode(), e.getMessage());
            }
        });
    }

    /**
     * 9.作业级别(更新频率：有变动就更新)
     * //todo 报错：
     * System.NullReferenceException: 未将对象引用设置到对象的实例。 在 BaSafetyApp.Controllers.Api.YH.YHExportApiController.
     * MethodJ(Import_WorkLevel_Search dto) 位置 D:\WorkSpace\C#\南通系统\BaSafetyPrj\BaSafetyApp\Controllers\Api\
     * YH\YHExportApiController.cs:行号 514
     */
    @Override
    public void workLevel(Map<OrgCodeBean, List<String>> map) {
        if (map == null || map.size() == 0) return;
        executor.execute(() -> {
            for (Map.Entry<OrgCodeBean, List<String>> entry : map.entrySet()) {
                OrgCodeBean codeBean = entry.getKey();
                List<String> list = entry.getValue();
                ShiroUser user = new ShiroUser();
                user.setTenentId(codeBean.getTenentId());
                //取的不定，两个都塞值
                user.setDepartCode(codeBean.getOrgCode());
                user.setCompanyCode(codeBean.getOrgCode());
                Context.setCurrentUser(user);
                Pair<String, DataAccessConfig> pair = getCode();
                String code = pair.getKey();
                if (code == null) return;
                Pair<Boolean, String> pair1 = getUrl(DataAccessTypes.WORK_LEVEL.getModelName());
                if (!pair1.getKey()) return;
                String url = pair1.getValue();
                JSONObject jsonObject = new JSONObject();
                JSONArray jsonArray = new JSONArray();
                jsonArray.addAll(list);
                jsonObject.put("WorkType", jsonArray);
                //WorkLevelBean bean = new WorkLevelBean(list);
                try {
                    APIResponseBean response = rest(code, jsonObject.toJSONString(), url);
                    if (response.getStatusCode() != HttpStatus.OK.value()) {
                        log.warn("work level access fail,workTypes:{},cause:{}", list, response.getMessage());
                        continue;
                    }
                    log.info("work level data access success,workTypes:{}", "");
                } catch (RestClientException e) {
                    log.error("work level data access fail,workTypes:{},cause:{}", list, e.getMessage());
                }
            }
        });
    }

    /**
     * 10.易燃易爆独栋厂房超员报警(更新频率：有变动就更新)
     * //无此模块，待开发，默认数据能通，可重复提交
     */
    @Override
    public void factoryOveralarm() {
        ShiroUser currentUser = Context.getCurrentUser();
        executor.execute(() -> {
            Context.setCurrentUser(currentUser);
            Pair<String, DataAccessConfig> pair = getCode();
            String code = pair.getKey();
            DataAccessConfig config = pair.getValue();
            if (code == null) return;
            Pair<Boolean, String> pair1 = getUrl(DataAccessTypes.FACTORY_OVER_ALARM.getModelName());
            if (!pair1.getKey()) return;
            String url = pair1.getValue();
            FactoryOveralarmBean bean = new FactoryOveralarmBean();
            bean.setQYID(config.getCompanyCode());
            bean.setQYMC(config.getCompanyName());
            bean.setAlertTime(SimpleDateFormatCache.getYmd().format(new Date()));
            bean.setAlertArea("3242");
            try {
                APIResponseBean response = rest(code, bean, url);
                if (response.getStatusCode() != HttpStatus.OK.value()) {
                    log.warn("factory over alarm data access fail,factoryOveralarm:{},cause:{}", "", response.getMessage());
                    return;
                }
                log.info("factory over alarm data access success,factoryOveralarm:{}", "");
            } catch (RestClientException e) {
                log.error("factory over alarm data access fail,factoryOveralarm:{},cause:{}", "", e.getMessage());
            }
        });
    }

    /**
     * 11.领导值班表(更新频率：每月更新)
     * 可重复提交
     */
    @Override
    public void leaderDutyTable(String formData, String formKeyLabelJson) {
        ShiroUser currentUser = Context.getCurrentUser();
        executor.execute(() -> {
            Context.setCurrentUser(currentUser);
            Pair<String, DataAccessConfig> pair = getCode();
            String code = pair.getKey();
            DataAccessConfig config = pair.getValue();
            if (code == null) return;
            Pair<Boolean, String> pair1 = getUrl(DataAccessTypes.LEADER_ON_DUTY_TABLE.getModelName());
            if (!pair1.getKey()) return;
            String url = pair1.getValue();
            DataAccessBeanY bean = getLeaderDutyTableBean(formData, formKeyLabelJson, config);
            String log1 = JSON.toJSONString(bean);
            try {
                APIResponseBean response = rest(code, bean, url);
                if (response.getStatusCode() != HttpStatus.OK.value()) {
                    log.warn("leader duty table data access fail,leaderDutyTable:{},cause:{}", log1, response.getMessage());
                    return;
                }
                log.info("leader duty table data access success,leaderDutyTable:{}", log1);
            } catch (RestClientException e) {
                log.error("leader duty table data access fail,leaderDutyTable:{},cause:{}", log1, e.getMessage());
            }
        });
    }

    /**
     * 12.领导带班值班记录(更新频率：有变动就更新)
     * 可重复提交
     */
    @Override
    public void leaderDutyRecord(String formData, String formKeyLabelJson) {
        ShiroUser currentUser = Context.getCurrentUser();
        executor.execute(() -> {
            Context.setCurrentUser(currentUser);
            Pair<String, DataAccessConfig> pair = getCode();
            String code = pair.getKey();
            DataAccessConfig config = pair.getValue();
            if (code == null) return;
            Pair<Boolean, String> pair1 = getUrl(DataAccessTypes.LEADER_ON_DUTY_RECORD.getModelName());
            if (!pair1.getKey()) return;
            String url = pair1.getValue();
            LeaderDutyRecordBean bean = getLeaderDutyRecordBean(formData, formKeyLabelJson, config);
            String log1 = JSON.toJSONString(bean);
            try {
                APIResponseBean response = rest(code, bean, url);
                if (response.getStatusCode() != HttpStatus.OK.value()) {
                    log.warn("leader duty record data access fail,leaderDutyRecord:{},cause:{}", log1, response.getMessage());
                    return;
                }
                log.info("leader duty record data access success,leaderDutyRecord:{}", log1);
            } catch (RestClientException e) {
                log.error("leader duty record data access fail,leaderDutyRecord:{},cause:{}", log1, e.getMessage());
            }
        });
    }

    /**
     * 13.风险培训记录(更新频率：有变动就更新)
     * 使用培训类型为：风险培训
     */
    @Override
    public void trainRecord(EduTrainningRecord record) {
        if (record == null) return;
        ShiroUser currentUser = Context.getCurrentUser();
        executor.execute(() -> {
            Context.setCurrentUser(currentUser);
            Pair<String, DataAccessConfig> pair = getCode();
            String code = pair.getKey();
            DataAccessConfig config = pair.getValue();
            if (code == null) return;
            Pair<Boolean, String> pair1 = getUrl(DataAccessTypes.RISK_TRAIN_RECORD.getModelName());
            if (!pair1.getKey()) return;
            String url = pair1.getValue();
            TrainRecordBean bean = getTrainRecordBean(record, config);
            try {
                APIResponseBean response = rest(code, bean, url);
                if (response.getStatusCode() != HttpStatus.OK.value()) {
                    log.warn("train record data access fail: recordId:{},cause:{}", record.getId(), response.getMessage());
                    return;
                }
                log.info("train record data access success,recordId:{}", record.getId());
            } catch (RestClientException e) {
                log.error("train record data access fail: recordId:{},cause:{}", record.getId(), e.getMessage());
            }
        });
    }

    /**
     * 14.应急演练记录(更新频率：有变动就更新)
     */
    @Override
    public void emergencyExerciseRecord(BpEmergencyExerciseRecord record) {
        if (record == null) return;
        ShiroUser currentUser = Context.getCurrentUser();
        executor.execute(() -> {
            Context.setCurrentUser(currentUser);
            Pair<String, DataAccessConfig> pair = getCode();
            String code = pair.getKey();
            DataAccessConfig config = pair.getValue();
            if (code == null) return;
            Pair<Boolean, String> pair1 = getUrl(DataAccessTypes.DRILL_TRAIN_RECORD.getModelName());
            if (!pair1.getKey()) return;
            String url = pair1.getValue();
            EmergencyExerciseRecordBean bean = getEmergencyExerciseRecordBean(record, config);
            try {
                APIResponseBean response = rest(code, bean, url);
                if (response.getStatusCode() != HttpStatus.OK.value()) {
                    log.warn("emergency exercise record data access fail,recordId:{},cause:{}", record.getId(), response.getMessage());
                    return;
                }
                log.info("emergency exercise record data access success,recordId:{}", record.getId());
            } catch (RestClientException e) {
                log.error("emergency exercise record data access fail,recordId:{},cause:{}", record.getId(), e.getMessage());
            }
        });
    }

    /**
     * 15.企业风险分区图(更新频率: 有变动就更新, 最长不超过 1 年)
     */
    @Override
    public void riskDistrict(String formData, String formKeyLabelJson) {
        ShiroUser currentUser = Context.getCurrentUser();
        executor.execute(() -> {
            Context.setCurrentUser(currentUser);
            Pair<String, DataAccessConfig> pair = getCode();
            String code = pair.getKey();
            DataAccessConfig config = pair.getValue();
            if (code == null) {
                return;
            }
            Pair<Boolean, String> pair1 = getUrl(DataAccessTypes.ENTERPRISE_RISK_DISTRICT.getModelName());
            if (!pair1.getKey()) {
                return;
            }
            String url = pair1.getValue();
            RiskDistrictBean bean = new RiskDistrictBean();
            bean.setQYID(config.getCompanyCode());
            bean.setQYMC(config.getCompanyName());
            JSONObject formDataObj = JSON.parseObject(formData);
            JSONObject formLabelObj = JSON.parseObject(formKeyLabelJson);
            bean.setRatingTime(getWorkFlowFieldValue(formDataObj, formLabelObj, "评定时间"));
            //流程引擎中存储的 图片url全路径
            String picUrl = getWorkFlowFieldValue(formDataObj, formLabelObj, "风险分区图");
            BaseImageRepository imageRepository = baseImageRespositoryDao.getOne(getImageId(picUrl));
            try {
                if (imageRepository != null) {
                    String imagePath = imageUploadPath + File.separator + imageRepository.getOriginPath();
                    FileInputStream fileInputStream = new FileInputStream(imagePath);
                    byte[] bytes = ByteStreams.toByteArray(fileInputStream);
                    String imageBase64 = Base64.getEncoder().encodeToString(bytes);
                    bean.setQYImage(imageBase64);
                }
                APIResponseBean response = rest(code, bean, url);
                if (response.getStatusCode() != HttpStatus.OK.value()) {
                    log.warn("risk district data access fail,cause:{}", response.getMessage());
                    return;
                }
                log.info("risk district data access success");
            } catch (RestClientException e) {
                log.error("risk district data access fail,cause:{}", e.getMessage());
            } catch (Exception e) {
                log.error("risk district data access fail,cause:{}", e.getMessage());
            }
        });
    }

    /**
     * 16.变更申请(更新频率：有变动就更新)
     * 可重复提交
     */
    @Override
    public void changeApply(String formData, String formKeyLabelJson) {
        ShiroUser currentUser = Context.getCurrentUser();
        executor.execute(() -> {
            Context.setCurrentUser(currentUser);
            Pair<String, DataAccessConfig> pair = getCode();
            String code = pair.getKey();
            DataAccessConfig config = pair.getValue();
            if (code == null) return;
            Pair<Boolean, String> pair1 = getUrl(DataAccessTypes.CHANGE_APPLY.getModelName());
            if (!pair1.getKey()) return;
            String url = pair1.getValue();
            ChangeApplyBean bean = getChangeApplyBean(formData, formKeyLabelJson, config);
            String log1 = JSON.toJSONString(bean);
            try {
                APIResponseBean response = rest(code, bean, url);
                if (response.getStatusCode() != HttpStatus.OK.value()) {
                    log.warn("change apply data access fail,changeApply:{},cause:{}", log1, response.getMessage());
                    return;
                }
                log.info("change apply data access success,changeApply:{}", log1);
            } catch (RestClientException e) {
                log.error("change apply data access fail,changeApply:{},cause:{}", log1, e.getMessage());
            }
        });
    }

    /**
     * 17.风险区域(更新频率：有变动就更新)
     * 不可以重复提交，即基于已有数据的update无效
     */
    @Override
    public void riskArea(List<RiskDistrict> districtList) {
        if (CollectionUtils.isEmpty(districtList)) return;
        ShiroUser currentUser = Context.getCurrentUser();
        executor.execute(() -> {
            Context.setCurrentUser(currentUser);
            Pair<String, DataAccessConfig> pair = getCode();
            String code = pair.getKey();
            DataAccessConfig config = pair.getValue();
            if (code == null) return;
            Pair<Boolean, String> pair1 = getUrl(DataAccessTypes.RISK_AREA.getModelName());
            if (!pair1.getKey()) return;
            String url = pair1.getValue();
            List<RiskAreaBean> beanList = districtList.stream().map(RiskAreaBean::new).collect(Collectors.toList());
            List<Long> districtIdList = districtList.stream().map(r -> r.getId()).collect(Collectors.toList());
            DataAccessBean bean = new DataAccessBean();
            bean.setCorpName(config.getCompanyName());
            bean.setCorpKey(config.getCompanyCode());
            bean.setDtos(beanList);
            try {
                APIResponseBean response = rest(code, bean, url);
                if (response.getStatusCode() != HttpStatus.OK.value()) {
                    log.warn("risk area data access fail,riskDistrictIds:{},cause:{}", districtIdList, response.getMessage());
                    return;
                }
                log.info("risk area data access success,riskDistrictIds:{}", districtIdList);
            } catch (RestClientException e) {
                log.error("risk area data access fail,riskDistrictIds:{},cause:{}", districtIdList, e.getMessage());
            }
        });
    }

    /**
     * 18.风险点(更新频率：有变动就更新)
     */
    @Override
    public void riskPoint(List<RiskPoint> riskPointList) {
        if (CollectionUtils.isEmpty(riskPointList)) return;
        ShiroUser currentUser = Context.getCurrentUser();
        executor.execute(() -> {
            Context.setCurrentUser(currentUser);
            Pair<String, DataAccessConfig> pair = getCode();
            String code = pair.getKey();
            DataAccessConfig config = pair.getValue();
            if (code == null) return;
            Pair<Boolean, String> pair1 = getUrl(DataAccessTypes.RISK_POINT.getModelName());
            if (!pair1.getKey()) return;
            String url = pair1.getValue();
            List<Long> riskPointIdList = riskPointList.stream().map(r -> r.getId()).collect(Collectors.toList());
            JSONObject jsonObject = getRiskPointJsonObject(riskPointList, config);
            try {
                APIResponseBean response = rest(code, jsonObject.toJSONString(), url);
                if (response.getStatusCode() != HttpStatus.OK.value()) {
                    log.warn("risk point data access fail,riskPointIds:{},cause:{}", riskPointIdList, response.getMessage());
                    return;
                }
                log.info("risk point data access success,riskPointIds:{}", riskPointIdList);
            } catch (RestClientException e) {
                log.error("risk point data access fail,riskPointIds:{},cause:{}", riskPointIdList, e.getMessage());
            }
        });
    }

    /**
     * 19.危险（有害）因素排查辨识清单(更新频率：有变动就更新)
     */
    @Override
    public void dangerInvestigate(RiskPoint riskPoint) {
        ShiroUser currentUser = Context.getCurrentUser();
        executor.execute(() -> {
            Context.setCurrentUser(currentUser);
            Pair<String, DataAccessConfig> pair = getCode();
            String code = pair.getKey();
            DataAccessConfig config = pair.getValue();
            if (code == null) return;
            Pair<Boolean, String> pair1 = getUrl(DataAccessTypes.DANGER_INVESTIGATE.getModelName());
            if (!pair1.getKey()) return;
            String url = pair1.getValue();
            String dangerInvestigateBean = getDangerInvestigateBean(riskPoint, config);
            try {
                APIResponseBean response = rest(code, dangerInvestigateBean, url);
                if (response.getStatusCode() != HttpStatus.OK.value()) {
                    log.warn("danger investigate data access fail,dangerInvestigate:{},cause:{}", dangerInvestigateBean, response.getMessage());
                    return;
                }
                log.info("danger investigate data access success,dangerInvestigate:{}", dangerInvestigateBean);
            } catch (RestClientException e) {
                log.error("danger investigate data access fail,dangerInvestigate:{},cause:{}", dangerInvestigateBean, e.getMessage());
            }
        });
    }

    /**
     * 20.风险管控清单(更新频率：有变动就更新)
     * 风险分级管控-分级管控按钮触发
     */
    @Override
    public void riskControl(RiskPoint point) {
        if (point == null) return;
        ShiroUser currentUser = Context.getCurrentUser();
        executor.execute(() -> {
            Context.setCurrentUser(currentUser);
            Pair<String, DataAccessConfig> pair = getCode();
            String code = pair.getKey();
            DataAccessConfig config = pair.getValue();
            if (code == null) return;
            Pair<Boolean, String> pair1 = getUrl(DataAccessTypes.RISK_CONTROL.getModelName());
            if (!pair1.getKey()) return;
            String url = pair1.getValue();
            DataAccessBean bean = getRiskControlBean(point, config);
            try {
                APIResponseBean response = rest(code, bean, url);
                if (response.getStatusCode() != HttpStatus.OK.value()) {
                    log.warn("risk point data access fail,riskPointId:{},cause:{}", point.getId(), response.getMessage());
                    return;
                }
                log.info("risk point data access success,riskPointId:{}", point.getId());
            } catch (RestClientException e) {
                log.error("risk point data access fail,riskPointId:{},cause:{}", point.getId(), e.getMessage());
            }
        });
    }

    /**
     * 21.三卡(更新频率：有变动就更新)
     * 不可重复提交
     */
    @Override
    public void threeCard(List<ThreeCardInBean> inBeanList) {
        if (CollectionUtils.isEmpty(inBeanList)) return;
        ShiroUser currentUser = Context.getCurrentUser();
        executor.execute(() -> {
            Context.setCurrentUser(currentUser);
            Pair<String, DataAccessConfig> pair = getCode();
            String code = pair.getKey();
            DataAccessConfig config = pair.getValue();
            if (code == null) return;
            Pair<Boolean, String> pair1 = getUrl(DataAccessTypes.THREE_CARD.getModelName());
            if (!pair1.getKey()) return;
            String url = pair1.getValue();
            DataAccessBean bean = getThreeCardBean(inBeanList, config);
            List<String> codeList = inBeanList.stream().map(r -> r.getCode()).collect(Collectors.toList());
            try {
                APIResponseBean response = rest(code, bean, url);
                if (response.getStatusCode() != HttpStatus.OK.value()) {
                    log.warn("three card data access fail,cardCodeList:{},cause:{}", codeList, response.getMessage());
                    return;
                }
                log.info("three card data access success,cardCodeList:{}", codeList);
            } catch (RestClientException e) {
                log.error("three card data access fail,cardCodeList:{},cause:{}", codeList, e.getMessage());
            }
        });
    }

    /**
     * 22.承包商管理(更新频率：有变动就更新)
     */
    @Override
    public void contractor(BpContractor bpContractor) {
        if (bpContractor == null) return;
        ShiroUser currentUser = Context.getCurrentUser();
        executor.execute(() -> {
            Context.setCurrentUser(currentUser);
            Pair<String, DataAccessConfig> pair = getCode();
            String code = pair.getKey();
            DataAccessConfig config = pair.getValue();
            if (code == null) return;
            Pair<Boolean, String> pair1 = getUrl(DataAccessTypes.CONTRACTOR_MANAGER.getModelName());
            if (!pair1.getKey()) return;
            String url = pair1.getValue();
            ContractorBean bean = getContractorBean(bpContractor, config);
            try {
                APIResponseBean response = rest(code, bean, url);
                if (response.getStatusCode() != HttpStatus.OK.value()) {
                    log.warn("contractor data access fail,contractorId:{},cause:{}", bpContractor.getId(), response.getMessage());
                    return;
                }
                log.info("contractor data access success,contractorId:{}", bpContractor.getId());
            } catch (RestClientException e) {
                log.error("contractor data access fail,contractorId:{},cause:{}", bpContractor.getId(), e.getMessage());
            }
        });
    }

    private DataAccessBeanV getSceneTrainBean(EduTrainningRecord record, DataAccessConfig config) {
        DataAccessBeanV bean = new DataAccessBeanV();
        bean.setCorpKey(config.getCompanyCode());
        bean.setCorpName(config.getCompanyName());
        SceneTrainBean sceneTrainBean = new SceneTrainBean();
        EduTrainningPlan plan = eduTrainningPlanDao.getOne(record.getTrainningPlanId());
        sceneTrainBean.setName(plan.getName());
        SimpleDateFormat format = SimpleDateFormatCache.getYmdhms();
        sceneTrainBean.setStartTime(format.format(plan.getImplementTime()));
        sceneTrainBean.setEndTime(format.format(plan.getFinishTime()));
//        List<EduTrainningRecordUser> recordUsers = trainningRecordUserDao.findByTrainningRecordId(record.getId());
//        List<SceneTrainUserBean> userBeans = Lists.newArrayList();
//        for (EduTrainningRecordUser user : recordUsers) {
//            SceneTrainUserBean trainUserBean = new SceneTrainUserBean();
//            Integer userContractorFlag = user.getUserContractorFlag();
//            Long userId = user.getUserId();
//            if (userContractorFlag == null || userContractorFlag == 0) {
//                BaseUser one = baseUserDao.getOne(userId);
//                trainUserBean.setIdentification(one.getIdCardNo());
//                trainUserBean.setUserName(one.getRealName());
//            } else {
//                BpContractorStaff one = staffDao.getOne(userId);
//                trainUserBean.setIdentification(one.getIdCardNo());
//                trainUserBean.setUserName(one.getName());
//            }
//            userBeans.add(trainUserBean);
//        }
//        sceneTrainBean.setUserDtos(userBeans);
        bean.setDtos(Lists.newArrayList(sceneTrainBean));
        return bean;
    }

//    private void setEvaluationData(RiskPoint riskPoint, RiskPointBean riskPointBean, RiskPointEvaluationDetailBean detailBean) {
//        riskPointBean.setPingGuRen(detailBean.getAnalyzeUserName());
//        String analyzeTime = detailBean.getAnalyzeTime();
//        riskPointBean.setPingGuTime(analyzeTime.substring(0, analyzeTime.indexOf(" ")));
//        RiskPointEvaluationBean scl = detailBean.getScl();
//        if (scl != null) {
//            //第一条级别最高
//            RiskPointEvaluationItemBean itemBean = scl.getItems().get(0);
//            riskPointBean.setLEC_L(itemBean.getLikehood() == null ? null : itemBean.getLikehood().toString());
//            riskPointBean.setLEC_E(itemBean.getExposure() == null ? null : itemBean.getExposure().toString());
//            riskPointBean.setLEC_C(itemBean.getConsequenceLevel() == null ? null : itemBean.getConsequenceLevel().toString());
//            riskPointBean.setLEC_D(itemBean.getDanger() == null ? null : itemBean.getDanger().toString());
//        }
//        RiskPointEvaluationBean jha = detailBean.getJha();
//        if (jha != null) {
//            RiskPointEvaluationItemBean itemBean = jha.getItems().get(0);
//            riskPointBean.setLS_L(itemBean.getLikehood() == null ? null : itemBean.getLikehood().toString());
//            riskPointBean.setLS_S(itemBean.getSeverity() == null ? null : itemBean.getSeverity().toString());
//            riskPointBean.setLS_R(itemBean.getRiskValue() == null ? null : itemBean.getRiskValue().toString());
//        }
//        //复评时间
//        RiskEvaluationPlan plan = riskEvaluationPlanDao.findFirstByRiskPointId(riskPoint.getId(), Sort.by(Sort.Order.desc("createTime")));
//        if (plan != null && plan.getNextEvaluationTime() != null) {
//            riskPointBean.setFuPingTime(SimpleDateFormatCache.getYmd().format(plan.getNextEvaluationTime()));
//        }
//    }

    private EmergencyExerciseRecordBean getEmergencyExerciseRecordBean(BpEmergencyExerciseRecord record, DataAccessConfig config) {
        EmergencyExerciseRecordBean bean = new EmergencyExerciseRecordBean();
        bean.setQYID(config.getCompanyCode());
        bean.setQYMC(config.getCompanyName());
        bean.setDrillContent(record.getContent());
        bean.setDrillTime(record.getDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        BpEmergencyExercisePlan plan = exercisePlanDao.getOne(record.getEpId());
        bean.setDrillAddress(plan.getLocation());
        //演练人员
        bean.setDrillPerson(getTrainUserName(record.getImplementerId()));
        return bean;
    }

    private DataAccessBeanY getLeaderDutyTableBean(String formData, String formKeyLabelJson, DataAccessConfig config) {
        DataAccessBeanY bean = new DataAccessBeanY();
        bean.setQYID(config.getCompanyCode());
        bean.setQYMC(config.getCompanyName());
        JSONObject formDataObj = JSON.parseObject(formData);
        JSONObject formLabelObj = JSON.parseObject(formKeyLabelJson);
        LeaderDutyTableBean leaderDutyTableBean = new LeaderDutyTableBean();
        leaderDutyTableBean.setZhiWu(getWorkFlowFieldValue(formDataObj, formLabelObj, "职务"));
        leaderDutyTableBean.setName(getWorkFlowFieldValue(formDataObj, formLabelObj, "姓名"));
        leaderDutyTableBean.setStartTime(getWorkFlowFieldValue(formDataObj, formLabelObj, "班次开始时间"));
        leaderDutyTableBean.setEndTime(getWorkFlowFieldValue(formDataObj, formLabelObj, "班次结束时间"));
        bean.setDtos(Lists.newArrayList(leaderDutyTableBean));
        return bean;
    }

    private DataAccessBeanV getDataAccessBeanV(String formData, String formKeyLabelJson, DataAccessConfig config) {
        DataAccessBeanV bean = new DataAccessBeanV();
        bean.setCorpKey(config.getCompanyCode());
        bean.setCorpName(config.getCompanyName());
        SafeInputBean safeInputBean = new SafeInputBean();
        JSONObject formDataObj = JSON.parseObject(formData);
        JSONObject formLabelObj = JSON.parseObject(formKeyLabelJson);
        safeInputBean.setTheYear(Integer.valueOf(getWorkFlowFieldValue(formDataObj, formLabelObj, "年度")));
        safeInputBean.setPutTime(getWorkFlowFieldValue(formDataObj, formLabelObj, "投入时间"));
        safeInputBean.setProjectName(getWorkFlowFieldValue(formDataObj, formLabelObj, "投入项目的名称"));
        safeInputBean.setProjectMoney(Double.valueOf(getWorkFlowFieldValue(formDataObj, formLabelObj, "投入资金")));
        bean.setDtos(Lists.newArrayList(safeInputBean));
        return bean;
    }

    private LeaderDutyRecordBean getLeaderDutyRecordBean(String formData, String formKeyLabelJson, DataAccessConfig config) {
        LeaderDutyRecordBean bean = new LeaderDutyRecordBean();
        bean.setQYID(config.getCompanyCode());
        bean.setQYMC(config.getCompanyName());
        JSONObject formDataObj = JSON.parseObject(formData);
        JSONObject formLabelObj = JSON.parseObject(formKeyLabelJson);
        bean.setZhiWu(getWorkFlowFieldValue(formDataObj, formLabelObj, "领导职务"));
        bean.setName(getWorkFlowFieldValue(formDataObj, formLabelObj, "领导姓名"));
        bean.setInTime(getWorkFlowFieldValue(formDataObj, formLabelObj, "进入生产区时间"));
        bean.setOutTime(getWorkFlowFieldValue(formDataObj, formLabelObj, "离开生产区时间"));
        return bean;
    }

    private HiddenDangerReportBean getHiddenDangerReportBean(DataAccessConfig config, JSONObject formDataObj, JSONObject formLabelObj) {
        // 隐患级别： 一般隐患C 不上报
        String level = getWorkFlowFieldValue(formDataObj, formLabelObj, "隐患级别");
        if("一般隐患C".equals(level)){
            return null;
        }
        HiddenDangerReportBean bean = new HiddenDangerReportBean();
        bean.setQYID(config.getCompanyCode());
        bean.setQYMC(config.getCompanyName());
        bean.setYHLB("基础管理");
        bean.setPCRQ(getWorkFlowFieldValue(formDataObj, formLabelObj, "上报时间"));
        bean.setYHBW(getWorkFlowFieldValue(formDataObj, formLabelObj, "发生环节"));
        bean.setYHDD(getWorkFlowFieldValue(formDataObj, formLabelObj, "隐患位置"));
        bean.setXCMS(getWorkFlowFieldValue(formDataObj, formLabelObj, "隐患名称"));
        bean.setZRDW(getWorkFlowFieldValue(formDataObj, formLabelObj, "责任单位"));
        bean.setZGZRR(getWorkFlowFieldValue(formDataObj, formLabelObj, "整改责任人"));
        bean.setZGLX(getWorkFlowFieldValue(formDataObj, formLabelObj, "整改方式"));
        bean.setZGQX(getWorkFlowFieldValue(formDataObj, formLabelObj, "要求完成日期"));
        bean.setJCRY(getWorkFlowFieldValue(formDataObj, formLabelObj, "上报人员"));
        bean.setDJSJ(getWorkFlowFieldValue(formDataObj, formLabelObj, "上报时间"));
        bean.setBZ(getWorkFlowFieldValue(formDataObj, formLabelObj, "整改情况"));
        bean.setYBYHZGQK(getWorkFlowFieldValue(formDataObj, formLabelObj, "整改情况"));
        bean.setYBYHZGCS(getWorkFlowFieldValue(formDataObj, formLabelObj, "整改措施"));
        bean.setYBYHZGSJ(getWorkFlowFieldValue(formDataObj, formLabelObj, "整改完成日期"));
        return bean;
    }

    private String getTrainUserName(String implementerId) {
        String[] split = implementerId.split(",");
        List<Long> userIds = Arrays.asList(split).stream().map(r -> Long.parseLong(r)).collect(Collectors.toList());
        List<String> nameList = baseUserDao.findRealNameByIdIn(userIds);
        return Joiner.on(",").join(nameList);
    }

    private ChangeApplyBean getChangeApplyBean(String formData, String formKeyLabelJson, DataAccessConfig config) {
        ChangeApplyBean bean = new ChangeApplyBean();
        bean.setQYID(config.getCompanyCode());
        bean.setQYMC(config.getCompanyName());
        JSONObject formDataObj = JSON.parseObject(formData);
        JSONObject formLabelObj = JSON.parseObject(formKeyLabelJson);
        bean.setBGXM(getWorkFlowFieldValue(formDataObj, formLabelObj, "企业编号"));
        bean.setXMBH(getWorkFlowFieldValue(formDataObj, formLabelObj, "项目编号"));
        bean.setBGLB(getWorkFlowFieldValue(formDataObj, formLabelObj, "变更类别"));
        bean.setSQR(getWorkFlowFieldValue(formDataObj, formLabelObj, "申请人"));
        bean.setSQBM(getWorkFlowFieldValue(formDataObj, formLabelObj, "申请部门"));
        bean.setSQSJ(getWorkFlowFieldValue(formDataObj, formLabelObj, "申请日期"));
        bean.setBGNRMS(getWorkFlowFieldValue(formDataObj, formLabelObj, "变更内容描述"));
        bean.setBGYY(getWorkFlowFieldValue(formDataObj, formLabelObj, "变更原因"));
        bean.setWHSBFXPGJG(getWorkFlowFieldValue(formDataObj, formLabelObj, "结果"));
        bean.setFXFXJKZCS(getWorkFlowFieldValue(formDataObj, formLabelObj, "风险分析及控制措施"));
        bean.setBGFA(getWorkFlowFieldValue(formDataObj, formLabelObj, "变更方案"));
        bean.setBMLDYJ(getWorkFlowFieldValue(formDataObj, formLabelObj, "部门领导意见"));
        bean.setZGBMYJ(getWorkFlowFieldValue(formDataObj, formLabelObj, "主管部门意见"));
        bean.setSSRYYJ(getWorkFlowFieldValue(formDataObj, formLabelObj, "实施人员意见"));
        bean.setGSLDYJ(getWorkFlowFieldValue(formDataObj, formLabelObj, "公司领导意见"));

        ChangeApplyAuditBean auditBean = new ChangeApplyAuditBean();
        auditBean.setBGXM(getWorkFlowFieldValue(formDataObj, formLabelObj, "变更项目"));
        auditBean.setBGSZBM(getWorkFlowFieldValue(formDataObj, formLabelObj, "变更所在部门"));
        auditBean.setZZYSBM(getWorkFlowFieldValue(formDataObj, formLabelObj, "组织验收部门"));
        auditBean.setYSRQ(getWorkFlowFieldValue(formDataObj, formLabelObj, "验收日期"));
        auditBean.setYSRY(getWorkFlowFieldValue(formDataObj, formLabelObj, "验收人员"));
        auditBean.setYSRYSZBM(getWorkFlowFieldValue(formDataObj, formLabelObj, "验收人员所在部门"));
        auditBean.setYSRYZW(getWorkFlowFieldValue(formDataObj, formLabelObj, "验收人员职务"));
        auditBean.setYSYJ(getWorkFlowFieldValue(formDataObj, formLabelObj, "验收意见"));
        auditBean.setYSBG(getWorkFlowFieldValue(formDataObj, formLabelObj, "验收报告"));
        auditBean.setZGBMYJ(getWorkFlowFieldValue(formDataObj, formLabelObj, "主管部门意见"));
        auditBean.setBGJGXYGTBM(getWorkFlowFieldValue(formDataObj, formLabelObj, "变更结果需要沟通部门"));
        auditBean.setGTBMYJ(getWorkFlowFieldValue(formDataObj, formLabelObj, "沟通部门意见"));
        auditBean.setBMLDYJ(getWorkFlowFieldValue(formDataObj, formLabelObj, "部门领导意见"));
        auditBean.setGSLDYJ(getWorkFlowFieldValue(formDataObj, formLabelObj, "公司领导意见"));
        bean.setChangeAcceptList(Lists.newArrayList(auditBean));
        return bean;
    }

    private LawStandardReportBean getLawStandardReportBean(String formData, String formKeyLabelJson, DataAccessConfig config) {
        LawStandardReportBean bean = new LawStandardReportBean();
        JSONObject formDataObj = JSON.parseObject(formData);
        JSONObject formLabelObj = JSON.parseObject(formKeyLabelJson);
        bean.setCorpKey(config.getCompanyCode());
        bean.setCorpName(config.getCompanyName());
        bean.setName(getWorkFlowFieldValue(formDataObj, formLabelObj, "文档名称"));
        bean.setScope(getWorkFlowFieldValue(formDataObj, formLabelObj, "适用部门"));
        bean.setIssueDept(getWorkFlowFieldValue(formDataObj, formLabelObj, "发布部门"));
        bean.setIssueDate(getWorkFlowFieldValue(formDataObj, formLabelObj, "发布日期"));
        bean.setAssessDate(getWorkFlowFieldValue(formDataObj, formLabelObj, "发布日期"));
        return bean;
    }

    private JSONObject getRiskPointJsonObject(List<RiskPoint> riskPointList, DataAccessConfig config) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("CorpKey", config.getCompanyCode());
        jsonObject.put("CorpName", config.getCompanyName());
        JSONArray jsonArray = new JSONArray();
        for (RiskPoint riskPoint : riskPointList) {
            JSONObject object = new JSONObject();
            object.put("RegionCode", riskPoint.getRiskDistrict().getCode());
            object.put("SpotCode", riskPoint.getCode());
            object.put("SpotName", riskPoint.getName());
            object.put("Position", "1");
            object.put("SpotGrade", "1");
            object.put("LEC_L", "1");
            object.put("LEC_E", "1");
            object.put("LEC_C", "1");
            object.put("LEC_D", "1");
            object.put("LS_L", "1");
            object.put("LS_S", "1");
            object.put("LS_R", "1");
            object.put("PingGuRen", "1");
            String time = SimpleDateFormatCache.getYmd().format(new Date());
            object.put("PingGuTime", time);
            object.put("FuPingTime", time);
            jsonArray.add(object);
        }
        jsonObject.put("Dtos", jsonArray);
        return jsonObject;
    }

    private TrainRecordBean getTrainRecordBean(EduTrainningRecord record, DataAccessConfig config) {
        TrainRecordBean bean = new TrainRecordBean();
        bean.setQYID(config.getCompanyCode());
        bean.setQYMC(config.getCompanyName());
        Long trainningPlanId = record.getTrainningPlanId();
        EduTrainningPlan plan = eduTrainningPlanDao.getOne(trainningPlanId);
        bean.setTrainContent(plan.getContent());
        SimpleDateFormat simpleDateFormat = SimpleDateFormatCache.getYmd();
        Date trainningDate = record.getTrainningDate();
        bean.setTrainTime(simpleDateFormat.format(trainningDate));
        bean.setTrainAddress(record.getTrainningPlace());
        //培训人员，多个都查出来 list->json ，没有默认'全体操作工'
        List<EduTrainningRecordUser> userList = eduTrainningRecordUserDao.findByTrainningRecordId(record.getId());
        if (CollectionUtils.isEmpty(userList)) {
            bean.setTrainPerson("全体操作工");
        } else {
            List<String> collect = userList.stream().map(r -> {
                Integer userContractorFlag = r.getUserContractorFlag();
                if (userContractorFlag == null || userContractorFlag == 0) {
                    return baseUserDao.getRealNameById(r.getUserId());
                } else {
                    return staffDao.findNameById(r.getUserId());
                }
            }).collect(Collectors.toList());
            bean.setTrainPerson(Joiner.on(",").join(collect));
        }
        return bean;
    }

    private WorkApplyBean getWorkApplyBean(BpWorkSafetyCert cert, DataAccessConfig config) {
        WorkApplyBean bean = new WorkApplyBean();
        bean.setQYID(config.getCompanyCode());
        bean.setQYMC(config.getCompanyName());
        bean.setWorkType(cert.getType());
        bean.setWorkName(cert.getType());
        bean.setWorkLevel(WorkLevels.findNameById(cert.getWorkLevel()));
        bean.setWorkNO(cert.getCode());
        BpWorkSafetyPeopleTypeBean peopleTypeBean = StringUtils.isEmpty(cert.getPeopleTypeJson()) ? null :
                JSONObject.parseObject(cert.getPeopleTypeJson(), BpWorkSafetyPeopleTypeBean.class);
        //监护人,作业负责人 还需要分本公司，承包商
        String monitorUserCode = cert.getMonitorUserCode();
        if (!StringUtils.isEmpty(monitorUserCode)) {
            long userId = Long.parseLong(monitorUserCode);
            String monitorUser = null;
            //盲板抽堵监护人是两个
            if (SafetyWorkTypes.MANG_BAN_CHOU_DU.getName().equals(cert.getType())) {
                if (peopleTypeBean == null || peopleTypeBean.getBlockMonitorUserType() == 0
                        || peopleTypeBean.getBlockMonitorUserType() == null) {
                    monitorUser = baseUserDao.getRealNameById(userId) + ",";
                } else {
                    String staffName = staffDao.getOne(userId).getName();
                    monitorUser = monitorUser == null ? staffName : monitorUser + staffName;
                }
            } else {
                if (peopleTypeBean == null || peopleTypeBean.getOpMonitorUserType() == 0 ||
                        peopleTypeBean.getOpMonitorUserType() == null) {
                    monitorUser = baseUserDao.getRealNameById(userId);
                } else {
                    monitorUser = staffDao.getOne(userId).getName();
                }
            }
            bean.setWorkGuardian(monitorUser);
        }
        //bean.setWorkFZR();
        bean.setWorkAddress(cert.getLocationCoords());
        SimpleDateFormat dateFormat = SimpleDateFormatCache.getYmdhms();
        bean.setWorkStartDate(dateFormat.format(cert.getStartTime()));
        bean.setWorkEndDate(dateFormat.format(cert.getEndTime()));
        bean.setWorkContent(cert.getWorkContent());
        //作业人类型决定作业单位类型：作业单位类型(本企业/作业方)，从作业人中选取，有一个即算，都有则'本企业,作业方'，没有默认本企业
        List<BpWorkSafetyCertUser> users = bpWorkSafetyCertUserDao.findByWorkId(cert.getId());
        Integer flag1 = 0;
        Integer flag2 = 0;
        if (CollectionUtils.isEmpty(users)) {
            bean.setWorkCorpType("本企业");
        } else {
            for (BpWorkSafetyCertUser user : users) {
                if (user.getUserType() != null && user.getUserType() == 1) {
                    //承包商
                    flag1 = 1;
                } else {
                    //本公司
                    flag2 = 1;
                }
            }
        }
        if (flag1.equals(1) && flag2.equals(1)) {
            bean.setWorkCorpType("本企业,作业方");
        } else if (flag1.equals(1) && flag2.equals(0)) {
            bean.setWorkCorpType("作业方");
        } else if (flag1.equals(0) && flag2.equals(1)) {
            bean.setWorkCorpType("本企业");
        }
        Long departId = cert.getApplyDepartId();
        bean.setWorkCorpName(departId == null ? null : bpDepartDao.getNameById(departId));
        return bean;
    }

    private DataAccessBean getRiskControlBean(RiskPoint point, DataAccessConfig config) {
        DataAccessBean bean = new DataAccessBean();
        bean.setCorpName(config.getCompanyName());
        bean.setCorpKey(config.getCompanyCode());
        RiskControlBean controlBean = new RiskControlBean();
        controlBean.setId(point.getCode());
        controlBean.setRegionCode(point.getRiskDistrict().getCode());
        controlBean.setSpotCode(point.getCode());
        controlBean.setName(point.getName());
        RiskPointEvaluationDetailBean detailBean = riskPointService.queryEvaluationDetail(point.getId());
        RiskPointEvaluationBean jha = detailBean.getJha();
        List<String> result = Lists.newArrayList();
        if (jha != null && !CollectionUtils.isEmpty(jha.getItems())) {
            for (RiskPointEvaluationItemBean item : jha.getItems()) {
                String controlMethodManage = item.getControlMethodManage();
                if (controlMethodManage != null) {
                    result.add(controlMethodManage);
                }
            }
        }
        RiskPointEvaluationBean scl = detailBean.getScl();
        if (scl != null && !CollectionUtils.isEmpty(scl.getItems())) {
            for (RiskPointEvaluationItemBean item : scl.getItems()) {
                String controlMethodManage = item.getControlMethodManage();
                if (controlMethodManage != null) {
                    result.add(controlMethodManage);
                }
            }
        }
        String join = Joiner.on(",").join(result);
        controlBean.setCuoShi(join);
        controlBean.setZeRenBuMen(point.getResponsibleDepart().getName());
        controlBean.setZeRenRen(point.getResponsibleUser().getRealName());
        bean.setDtos(Lists.newArrayList(controlBean));
        return bean;
    }

    private DataAccessBean getThreeCardBean(List<ThreeCardInBean> inBeanList, DataAccessConfig config) {
        DataAccessBean bean = new DataAccessBean();
        bean.setCorpName(config.getCompanyName());
        bean.setCorpKey(config.getCompanyCode());
        List<ThreeCardBean> threeCardBeanList = Lists.newArrayList();
        for (ThreeCardInBean card : inBeanList) {
            ThreeCardBean cardBean = new ThreeCardBean();
            cardBean.setId(card.getCode());
            cardBean.setName(card.getPicName());
            Long riskDistrictId = card.getRiskDistrictId();
            RiskDistrict riskDistrict = riskDistrictDao.getOne(riskDistrictId);
            if (riskDistrict != null && riskDistrict.getCode() != null) {
                cardBean.setRegionCode(riskDistrict.getCode());
            }
            BaseImageRepository imageRepository = baseImageRespositoryDao.getOne(card.getPicId());
            if (imageRepository != null) {
                String imagePath = imageUploadPath + File.separator + imageRepository.getOriginPath();
                try {
                    FileInputStream fileInputStream = new FileInputStream(imagePath);
                    byte[] bytes = ByteStreams.toByteArray(fileInputStream);
                    String imageBase64 = Base64.getEncoder().encodeToString(bytes);
                    cardBean.setImgUrl(imageBase64);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            threeCardBeanList.add(cardBean);
        }
        bean.setDtos(threeCardBeanList);
        return bean;
    }

    private ContractorBean getContractorBean(BpContractor bpContractor, DataAccessConfig config) {
        ContractorBean bean = new ContractorBean();
        bean.setCorpKey(config.getCompanyCode());
        bean.setCorpName(config.getCompanyName());
        bean.setName(bpContractor.getCompanyName());
        bean.setAddress(bpContractor.getCompanyAddress());
        bean.setLegalPerson(bpContractor.getCompanyLegalPerson());
        bean.setPhone(bpContractor.getContractorTel());
        //资质等级如果没有，默认最低等级--三级  --暂时不必填的可以不做
        bean.setCertificateNO(bpContractor.getCode());
        bean.setBusinessScope(bpContractor.getBusinessScope());
        return bean;
    }

    private String getWorkFlowFieldValue(JSONObject formDataObj, JSONObject formLabelObj, String label) {
        if (formDataObj == null || formLabelObj == null) {
            return "";
        }
        if (formLabelObj.getString(label) == null) {
            return "";
        }
        return formDataObj.getString(formLabelObj.getString(label));
    }

    private Long getImageId(String picUrl) {
        if (picUrl.contains("=") && picUrl.contains("id")) {
            List<String> strings = JSON.parseArray(picUrl, String.class);
            if (!CollectionUtils.isEmpty(strings)) {
                String s = strings.get(0);
                return Long.valueOf(s.substring(s.lastIndexOf("=") + 1));
            }
        }
        return null;
    }

    private String getDangerInvestigateBean(RiskPoint riskPoint, DataAccessConfig config) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("CorpKey", config.getCompanyCode());
        jsonObject.put("CorpName", config.getCompanyName());
        JSONArray jsonArray = new JSONArray();
        JSONObject object = new JSONObject();
        object.put("Id", riskPoint.getCode());
        object.put("RegionCode", riskPoint.getRiskDistrict().getCode());
        object.put("SpotCode", riskPoint.getCode());
        object.put("Name", riskPoint.getName());
        object.put("ZuoYeHuoDong", "作业活动".equals(riskPoint.getType()) ? "是" : "否");
        object.put("WeiXianYinSu", riskPoint.getUnstandardSituationConsequence());
        object.put("State", "正常");
        object.put("DaoZhiShiGu", riskPoint.getAccidentType());
        object.put("SheJiXiangGuanFang", "无");
        jsonArray.add(object);
        jsonObject.put("Dtos", jsonArray);
        return jsonObject.toJSONString();
    }

    private APIResponseBean rest(String code, Object bean, String url) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("code", code);
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity httpEntity = new HttpEntity(bean, httpHeaders);
        return restTemplate.postForObject(url, httpEntity, APIResponseBean.class);
    }

    public DataAccessConfig getConfig() {
        return configService.getByOrgCode();
    }

    /**
     * 不在 安全防护设备/安全防护 消防设备/消防 4种之一
     */
    private boolean judge(String facilityName) {
        if (!facilityName.equals("安全防护设备") && !facilityName.equals("安全防护") &&
                !facilityName.equals("消防设备") && !facilityName.equals("消防")) {
            return true;
        }
        return false;
    }

    @Override
    public boolean isOpen() {
        DataAccessConfig config = getConfig();
        if (config == null) {
            return false;
        }
        return config.getStatus();
    }

    @Override
    public boolean isWorkLevelOpen() {
        Pair<Boolean, String> url = getUrl(DataAccessTypes.WORK_LEVEL.getModelName());
        return url.getKey();
    }

    /**
     * 获取模块对应接口url
     */
    public Pair<Boolean, String> getUrl(String modelName) {
        List<DataAccessUrl> list = dataAccessUrlService.findAllUrl();
        if (CollectionUtils.isEmpty(list)) {
            return new Pair<>(false, null);
        }
        for (DataAccessUrl dataAccessUrl : list) {
            if (modelName.equals(dataAccessUrl.getName())) {
                return new Pair<>(dataAccessUrl.getStatus(), dataAccessUrl.getUrl());
            }
        }
        return new Pair<>(false, null);
    }

}
